const rp = require('request-promise')
const fs = require('fs')
const schedule = require('node-schedule')
const { wx } = require('../config')

const updateTicket = (access_token) => {
  const type = 'jsapi'
  rp({
    uri: `${wx.host}/cgi-bin/ticket/getticket`,
    qs: { access_token, type },
    json: true
  }).then(res => {
    let { ticket } = res
    fs.writeFileSync(wx.ticketPath, ticket)
  }).catch(err => {
    console.log(err)
  })
}

const updateToken = () => {
  const {  appid, secret } = wx
  const grant_type = 'client_credential'
  rp({
    uri: `${wx.host}/cgi-bin/token`,
    qs: { appid, secret, grant_type },
    json: true
  }).then(res => {
    let { access_token } = res
    fs.writeFileSync(wx.tokenPath, access_token)
    updateTicket(access_token)
  }).catch(err => {
    console.log(err)
  })
}

// 获取token
const getToken = () => {
  const token = fs.readFileSync(wx.tokenPath, 'utf-8')
  return token
}

// 获取ticket
const getJsApiTicket = () => {
  const ticket = fs.readFileSync(wx.ticketPath, 'utf-8')
  return ticket
}

updateToken()

// 定时刷新token
let rule = new schedule.RecurrenceRule()
rule.hour = [0, new schedule.Range(1, 23)]
schedule.scheduleJob(rule, () => {
  updateToken()
})

module.exports = {
  getToken,
  getJsApiTicket
}